package com.baijiayun.liveuibase.widgets.courseware;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baijiahulian.common.cropperv2.BJCommonImageCropHelper;
import com.baijiahulian.common.cropperv2.ThemeConfig;
import com.baijiahulian.common.cropperv2.model.PhotoInfo;
import com.baijiahulian.common.networkv2.BJNetCallback;
import com.baijiahulian.common.networkv2.BJResponse;
import com.baijiahulian.common.networkv2.HttpException;
import com.baijiayun.livecore.context.LPConstants;
import com.baijiayun.livecore.context.LiveRoom;
import com.baijiayun.livecore.models.LPDocTranslateProgressModel;
import com.baijiayun.livecore.models.LPUploadingDocumentModel;
import com.baijiayun.livecore.models.courseware.LPMediaCoursewareModel;
import com.baijiayun.livecore.models.file.cloudfile.LPCloudFileModel;
import com.baijiayun.livecore.models.file.homework.LPResHomeworkAllModel;
import com.baijiayun.livecore.network.request.DownLoadManager;
import com.baijiayun.livecore.utils.DisplayUtils;
import com.baijiayun.livecore.viewmodels.impl.LPDocListViewModel;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.base.BaseUIConstant;
import com.baijiayun.liveuibase.base.BaseUIConstant.FileUploadState;
import com.baijiayun.liveuibase.base.BaseUIConstant.HomeworkDownloadState;
import com.baijiayun.liveuibase.base.BaseUIConstant.UploadType;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.baijiayun.liveuibase.utils.ToastUtil;
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder;
import com.baijiayun.liveuibase.utils.drawable.StateListDrawableBuilder;
import com.baijiayun.liveuibase.widgets.common.DirRecordTextView;
import com.baijiayun.liveuibase.widgets.courseware.models.TabState;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.ScrollBoundaryDecider;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.baijiayun.liveuibase.base.BaseUIConstant.ListState;
import static com.baijiayun.liveuibase.utils.FileOptUtil.checkAnimFilePathValid;
import static com.baijiayun.liveuibase.utils.FileOptUtil.checkStaticFilePathValid;
import static com.baijiayun.liveuibase.utils.BaseUIUtils.isImageFile;
import static com.baijiayun.liveuibase.widgets.courseware.models.TabState.CloudFile;
import static com.baijiayun.liveuibase.widgets.courseware.models.TabState.DocFile;
import static com.baijiayun.liveuibase.widgets.courseware.models.TabState.HomeworkFile;

public abstract class BaseCourseWareView extends Fragment implements BaseCourseWareContract.BaseCourseWareView
        , View.OnTouchListener {

    protected BaseCourseWareContract.BaseCourseWarePresenter presenter;
    private ICourseWareViewListener courseWareViewListener;

    protected TabState tabState = DocFile;

    protected Context context;
    protected View contentView;
    protected BaseCourseWareFileAdapter courseWareAdapter;
    protected BaseCourseWareUploadDialog uploadDialog;
    // 当前教室内是否为所有的学生都支持作业功能
    private boolean allIsSupportHomework = true;

    private List<LPCloudFileModel> dirRecordList = new ArrayList<>();

    public final static int REQUEST_CODE_PERMISSION_WRITE = 1;

    // region 作业支持弹窗，是否已点击不再提醒
    protected enum HomeworkRemindStatus {
        DoNotRemind,
        WaitingForRst,
        HasShowRst
    }

    protected HomeworkRemindStatus homeworkRemindStatus = HomeworkRemindStatus.HasShowRst;
    // endregion

    // region 控件id
    CheckBox cbEnableStudentUpload;
    View tabDocTab;
    View tabCloudTab;
    View tabHomeWork;
    EditText etSearcher;
    DirRecordTextView tvDirRecordMore;
    boolean isOnSearching = false;
    protected RecyclerView rlCourseware;
    protected SmartRefreshLayout smartRefreshLayout;

    private void initViewId() {
        cbEnableStudentUpload = contentView.findViewById(R.id.window_course_ware_enable_student_upload_check_box);
        tabHomeWork = contentView.findViewById(R.id.window_course_ware_homework_tab);
        rlCourseware = contentView.findViewById(R.id.window_course_ware_file_list_rl);
        smartRefreshLayout = contentView.findViewById(R.id.window_course_ware_file_refresh_layout);
        tabDocTab = contentView.findViewById(R.id.window_course_ware_class_files_tab);
        tabCloudTab = contentView.findViewById(R.id.window_course_ware_cloud_files_tab);
        etSearcher = contentView.findViewById(R.id.window_course_ware_searcher);
        tvDirRecordMore = contentView.findViewById(R.id.window_course_ware_record_dir_more);
        tvDirRecordMore.setOnItemClickListener(this::changeDirPosition);

        etSearcher.addTextChangedListener(new TextWatcher() {
            boolean hasChange;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                hasChange = count + after > 0;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // do nothing
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 重建 showDocumentList 避免操作 暂存的 list
                isOnSearching = !TextUtils.isEmpty(s);
                courseWareAdapter.setOnSearching(isOnSearching);
                etSearcher.removeCallbacks(homeworkSearchRunnable);
                etSearcher.removeCallbacks(cloudSearchRunnable);
                etSearcher.removeCallbacks(docSearchRunnable);
                if (isOnSearching) {
                    showContent(ListState.Requesting);
                } else {
                    showContent(getNowAdapterState());
                }
                if (tabState == HomeworkFile) {
                    // 作业搜索，因为 作业 list 没有一次性返回，所以需要请求服务器来搜索并返回搜索结果以显示
                    // 清除当前搜索结果
                    courseWareAdapter.updateHomeworkSearchRst(null);
                    if (isOnSearching) {
                        // 0.5 秒后请求搜索，避免每次输入都搜索，导致无意义的搜索过多
                        etSearcher.postDelayed(homeworkSearchRunnable, 500);
                    }
                } else if (tabState == CloudFile) {
                    // 云盘搜索，改为全局搜索，本地只有当前文件夹下的文件内容，需要请求
                    if (hasChange) {
                        if (isOnSearching) {
                            etSearcher.postDelayed(cloudSearchRunnable, 500);
                        } else {
                            getLiveRoom().getCloudFileVM().requestSearchFile(etSearcher.getText().toString(), true);
                        }
                    }
                } else {
                    // 教室文件，在本地list中遍历即可
                    if (isOnSearching) {
                        // 0.5 秒后再搜索，避免每次输入都搜索，导致无意义的搜索过多
                        etSearcher.postDelayed(docSearchRunnable, 500);
                    }
                }
                setVisibility(R.id.window_course_ware_search_clear, isOnSearching);
            }
        });
    }
    // endregion

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        context = getContext();
        contentView = LayoutInflater.from(context).inflate(R.layout.uibase_courseware_manage_layout, container, false);
        presenter = initPresenter();
        initChildData();
        initViewId();

        courseWareViewListener = initCourseWareViewListener();

        // region tab切换及 背景 drawable 初始化
        contentView.setOnTouchListener(this);
        contentView.findViewById(R.id.base_courseware_container).setBackground(
                ThemeDataUtil.getCommonWindowBg(context));
        contentView.findViewById(R.id.window_course_ware_close).setOnClickListener(v -> {
            if (courseWareViewListener != null) {
                courseWareViewListener.onClose();
            }
        });

        initTabView(tabDocTab, DocFile);
        initTabView(tabCloudTab, CloudFile);

        initCoursewareContainer();

        if (isEnableHomework()) {
            initTabView(tabHomeWork, HomeworkFile);
        } else {
            tabHomeWork.setVisibility(View.GONE);
        }

        // 默认允许上传
        updateAllowUpdateHomework(true);
        // endregion

        // region 是否允许学生上传
        contentView.findViewById(R.id.window_course_ware_enable_student_upload_tv).setOnClickListener(v ->
                cbEnableStudentUpload.performClick());
        cbEnableStudentUpload.setOnClickListener(v ->
                courseWareViewListener.onUpdateAllowUploadHomework(cbEnableStudentUpload.isChecked()));
        // endregion

        tabDocTab.setSelected(true);

        // region 点击外部收起键盘
        etSearcher.setOnEditorActionListener((v, actionId, event) -> {
            clearEditFocus(etSearcher);
            return true;
        });
        contentView.findViewById(R.id.window_course_ware_search_clear).setOnClickListener(v -> {
            clearEditFocus(etSearcher);
            etSearcher.setText("");
        });
        // endregion

        // region 上传打开文件管理系统请求
        contentView.findViewById(R.id.window_course_ware_upload).setOnClickListener(v -> {
            if (getLiveRoom().getCurrentUser().getType() == LPConstants.LPUserType.Assistant && !getLiveRoom().getAdminAuth().documentUpload) {
                showToast(getString(R.string.base_ui_forbid_upload_ppt));
                return;
            }
            if (tabState == HomeworkFile) {
                if (courseWareViewListener != null) {
                    courseWareViewListener.onUploadFile(UploadType.HomeWork);
                }
            } else {
                showUploadDialog();
            }
        });

        contentView.findViewById(R.id.window_course_ware_upload_image).setOnClickListener(v -> {
            checkPermission();
        });
        // endregion

        // region 其余点击事件
        contentView.findViewById(R.id.window_course_ware_refresh).setOnClickListener(v -> onRefreshDocList());
        contentView.findViewById(R.id.window_course_ware_record_dir_root).setOnClickListener(v -> {
            getLiveRoom().getCloudFileVM().requestCloudFileAll();
            showContent(ListState.Requesting);
            clearEditFocus(etSearcher);
            etSearcher.setText("");
        });
        // endregion

        showAsUserType();
        return contentView;
    }

    // region 视图变更

    /**
     * 按当前用户角色展示窗口
     */
    private void showAsUserType() {
        if (!isTeacherOrAssistant()) {
            // 非老师助教
            // 仅展示作业 tab
            updateTabView(HomeworkFile);
            // 不展示 tab 栏
            setVisibility(R.id.window_course_ware_tab_container, false);
            // 标题展示为 "作业区"
            TextView tvTitle = contentView.findViewById(R.id.base_course_ware_title);
            tvTitle.setText(R.string.base_course_manage_homework_tab);
            // 隐藏"学生上传控制组"
            cbEnableStudentUpload.setVisibility(View.GONE);
            setVisibility(R.id.window_course_ware_enable_student_upload_tv, false);
            // 隐藏搜索栏
            setVisibility(R.id.window_course_ware_search_container, false);
        } else if (!isOrganizationUser()) {
            // 老师助教，检查云盘功能是否可用
            tabCloudTab.setVisibility(View.GONE);
        }
    }

    /**
     * 刷新 当前列表
     */
    private void onRefreshDocList() {
        if (getLiveRoom() == null) {
            return;
        }
        showContent(ListState.Requesting);
        switch (tabState) {
            case DocFile:
                getLiveRoom().getDocListVM().requestDocAllReq();
                break;
            case CloudFile:
                getLiveRoom().getCloudFileVM().onRefresh();
                break;
            case HomeworkFile:
                // 刷新，不做其他操作，仅请求
                getLiveRoom().getDocListVM().requestRefreshDocList(this, new BJNetCallback() {
                    @Override
                    public void onFailure(HttpException e) {
                        contentView.post(() -> showContent(getNowAdapterState()));
                    }

                    @Override
                    public void onResponse(BJResponse bjResponse) {
                        contentView.post(() -> showContent(getNowAdapterState()));
                    }
                });
                break;
            default:
                break;
        }
    }

    private void showUploadDialog() {
        if (uploadDialog == null) {
            uploadDialog = new BaseCourseWareUploadDialog(context, new BaseCourseWareUploadDialog.IOnChooseUploadTypeListener() {
                @Override
                public void onChooseStatic() {
                    if (courseWareViewListener != null) {
                        courseWareViewListener.onUploadFile(tabState == CloudFile
                                ? UploadType.StaticCloudFile : UploadType.StaticDoc);
                    }
                }

                @Override
                public void onChooseAnim() {
                    if (courseWareViewListener != null) {
                        courseWareViewListener.onUploadFile(tabState == CloudFile
                                ? UploadType.AnimCloudFile : UploadType.AnimDoc);
                    }
                }
            });
        }
        if (!uploadDialog.isShowing()) {
            uploadDialog.show();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initCoursewareContainer() {
        rlCourseware.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView recyclerView, @NonNull MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    clearEditFocus(etSearcher);
                }
                return false;
            }

            @Override
            public void onTouchEvent(@NonNull RecyclerView recyclerView, @NonNull MotionEvent motionEvent) {
                // do nothing
            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean b) {
                // do nothing
            }
        });
        rlCourseware.setLayoutManager(new LinearLayoutManager(context));
        courseWareAdapter = new BaseCourseWareFileAdapter(
                courseWareViewListener, isTeacherOrAssistant(), context);
        courseWareAdapter.setPresenter(presenter);
        rlCourseware.setAdapter(courseWareAdapter);

        smartRefreshLayout.setEnableRefresh(false);
        ((ClassicsFooter) contentView.findViewById(R.id.window_course_ware_file_refresh_footer))
                .setAccentColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_assistant_text_color));
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            if (tabState == DocFile) {
                // 云盘和作业都需要加载分页
                smartRefreshLayout.finishLoadMore();
                return;
            }
            String keyword = isOnSearching ? etSearcher.getText().toString() : "";
            if (tabState == HomeworkFile) {
                courseWareViewListener.requestLoadNextPage(keyword);
            } else {
                // 云盘翻页
                getLiveRoom().getCloudFileVM().loadNextPage(keyword);
            }
            smartRefreshLayout.finishLoadMore(2000);
        });
        smartRefreshLayout.setScrollBoundaryDecider(new ScrollBoundaryDecider() {
            @Override
            public boolean canRefresh(View content) {
                return true;
            }

            @Override
            public boolean canLoadMore(View content) {
                if (rlCourseware == null) return false;
                //获取recyclerView的高度
                rlCourseware.getHeight();
                //整个View控件的高度
                int scrollRange = rlCourseware.computeVerticalScrollRange();
                //当前屏幕之前滑过的距离
                int scrollOffset = rlCourseware.computeVerticalScrollOffset();
                //当前屏幕显示的区域高度
                int scrollExtent = rlCourseware.computeVerticalScrollExtent();
                int height = rlCourseware.getHeight();
                if (height > scrollRange) {
                    return false;
                }
                return scrollRange <= scrollOffset + scrollExtent;
            }
        });
    }

    private void initTabView(View tabView, TabState tabState) {
        Drawable selectedDrawable = new DrawableBuilder()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .cornerRadii(DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 2), 0, 0)
                .build();
        Drawable normalDrawable = new DrawableBuilder()
                .strokeWidth(DisplayUtils.dip2px(context, 0.5f))
                .strokeColor(ContextCompat.getColor(context, R.color.base_bg_stroke))
                .cornerRadii(DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 2), 0, 0)
                .build();
        tabView.setOnClickListener(
                v -> updateTabView(tabState));
        tabView.setBackground(
                new StateListDrawableBuilder()
                        .normal(normalDrawable)
                        .selected(selectedDrawable)
                        .build());
    }

    /**
     * 作业搜索线程
     */
    Runnable homeworkSearchRunnable = () -> {
        // 向服务端申请搜索作业
        presenter.requestSearchHomework(etSearcher.getText().toString());
    };

    Runnable cloudSearchRunnable = () -> {
        // 申请全局搜索云盘文件
        if (getLiveRoom() != null) {
            getLiveRoom().getCloudFileVM().requestSearchFile(etSearcher.getText().toString(), true);
        }
    };

    /**
     * 文档搜索线程
     */
    Runnable docSearchRunnable = () -> {
        courseWareAdapter.updateDocSearchKeyword(etSearcher.getText().toString());
        showContent(getNowAdapterState());
    };

    /**
     * 更新 tab 状态
     */
    private void updateTabView(TabState tabState) {
        if (this.tabState != tabState) {
            // tab 变更
            if (tabState == HomeworkFile && isTeacherOrAssistant()) {
                if (allIsSupportHomework && homeworkRemindStatus != HomeworkRemindStatus.DoNotRemind) {
                    homeworkRemindStatus = HomeworkRemindStatus.WaitingForRst;
                    presenter.requestHomeworkSupport();
                } else if (homeworkRemindStatus == HomeworkRemindStatus.HasShowRst) {
                    courseWareViewListener.onRemindHomeworkSupport();
                }
            }
            if (tabState == CloudFile) {
                // 变更为云盘 tab， 重新请求
                getLiveRoom().getCloudFileVM().onRefresh();
                showContent(ListState.Requesting);
            }
        }
        this.tabState = tabState;
        courseWareAdapter.updateTabState(tabState);
        // region 更新tab
        tabDocTab.setSelected(tabState == DocFile);
        tabCloudTab.setSelected(tabState == CloudFile);
        tabHomeWork.setSelected(tabState == HomeworkFile);
        // endregion

        // region 清除搜索输入框
        etSearcher.setText("");
        etSearcher.setHint(tabState == HomeworkFile
                ? R.string.base_course_manage_homework_search_hint
                : R.string.base_course_manage_search_hint);
        ((TextView) contentView.findViewById(R.id.window_course_ware_upload_name)).setText(
                tabState == HomeworkFile ? R.string.base_course_manage_upload_homework_file
                        : R.string.base_course_manage_upload_file);
        clearEditFocus(etSearcher);
        // endregion

        // region 更新其他视图
        setVisibility(R.id.window_course_ware_tab_hint, tabState == HomeworkFile);
        setVisibility(R.id.window_course_ware_tab_hint_icon, tabState == HomeworkFile);
        setVisibility(R.id.window_course_ware_enable_student_upload_check_box, tabState == HomeworkFile);
        setVisibility(R.id.window_course_ware_enable_student_upload_tv, tabState == HomeworkFile);

        updateFinderRecordView();
        // endregion

        showContent(getNowAdapterState());
    }

    /**
     * 根据数据源是否为空或请求中，以及当前tab状态，刷新视图内各控件 visibility 属性
     *
     * @param listState 当前是否为空
     */
    private void showContent(ListState listState) {
        switch (listState) {
            case Empty: {
                // 空
                setVisibility(R.id.window_course_ware_empty_file_container, true);
                setVisibility(R.id.window_course_ware_loading, false);
                String emptyFileDes;
                if (isOnSearching) {
                    emptyFileDes = context.getString(tabState == HomeworkFile
                            ? R.string.base_course_manage_no_search_homework_file
                            : R.string.base_course_manage_no_search_file);
                } else {
                    emptyFileDes = context.getString(tabState == HomeworkFile
                            ? R.string.base_course_manage_no_homework_file
                            : R.string.base_course_manage_no_file);
                }
                ((TextView) contentView.findViewById(R.id.window_course_ware_empty_file_des)).setText(emptyFileDes);
                setVisibility(R.id.window_course_ware_file_refresh_layout, false);
                stopLoadingAnim();
                break;
            }
            case NotEmpty: {
                // 非空
                setVisibility(R.id.window_course_ware_empty_file_container, false);
                setVisibility(R.id.window_course_ware_loading, false);
                setVisibility(R.id.window_course_ware_file_refresh_layout, true);
                stopLoadingAnim();
                break;
            }
            case Requesting: {
                setVisibility(R.id.window_course_ware_empty_file_container, false);
                setVisibility(R.id.window_course_ware_loading, true);
                setVisibility(R.id.window_course_ware_file_refresh_layout, false);
                startLoadingAnim();
                break;
            }
            default:
                break;
        }
    }

    private void startLoadingAnim() {
        if (contentView.findViewById(R.id.window_course_ware_loading).getAnimation() != null) {
            return;
        }
        RotateAnimation rotate = new RotateAnimation(0f, 360f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        LinearInterpolator lin = new LinearInterpolator();
        rotate.setInterpolator(lin);
        rotate.setDuration(2000);
        rotate.setRepeatCount(-1);
        rotate.setFillAfter(true);
        contentView.findViewById(R.id.window_course_ware_loading).setAnimation(rotate);
        rotate.start();
    }

    private void stopLoadingAnim() {
        contentView.findViewById(R.id.window_course_ware_loading).clearAnimation();
    }

    /**
     * 更新当前面包屑相关视图
     */
    private void updateFinderRecordView() {
        boolean hideFinderRecordView = tabState != CloudFile || dirRecordList.size() == 0;
        setVisibility(R.id.window_course_ware_upload, hideFinderRecordView);
        setVisibility(R.id.window_course_ware_upload_image, hideFinderRecordView);
        setVisibility(R.id.window_course_ware_record_dir_root, !hideFinderRecordView);
        setVisibility(R.id.window_course_ware_record_dir_more, !hideFinderRecordView);
    }
    // endregion

    // region 需要子类实现的方法
    protected abstract void initChildData();

    /**
     * 初始化试图内事件监听器，由子类负责具体实现
     */
    protected abstract ICourseWareViewListener initCourseWareViewListener();

    /**
     * 初始化 presenter，由子类负责具体实现
     */
    protected abstract BaseCourseWareContract.BaseCourseWarePresenter initPresenter();

    protected abstract LiveRoom getLiveRoom();
    // endregion

    // region 子类数据变更调用

    /**
     * 学生上传文档权限变更回调
     */
    @Override
    public void updateAllowUpdateHomework(boolean isAllow) {
        cbEnableStudentUpload.setChecked(isAllow);
        if (!isTeacherOrAssistant()) {
            int visibility = isAllow ? View.VISIBLE : View.GONE;
            contentView.findViewById(R.id.window_course_ware_upload).setVisibility(visibility);
            contentView.findViewById(R.id.window_course_ware_upload_image).setVisibility(visibility);
        }
    }

    /**
     * 刷新 doc list
     */
    @Override
    public void updateAllDocList(@NotNull List<LPDocListViewModel.DocModel> allDocList) {
        courseWareAdapter.updateAllDocList(allDocList);
        showContent(getNowAdapterState());
    }

    @Override
    public void updateMediaCoursewareList(List<LPMediaCoursewareModel> mediaCoursewareModelList) {
        courseWareAdapter.updateMediaCoursewareList(mediaCoursewareModelList);
        showContent(getNowAdapterState());
    }

    /**
     * 刷新 homework list
     */
    @Override
    public void updateAllHomework(@NotNull LPResHomeworkAllModel homeworkAll) {
        courseWareAdapter.updateAllHomework(homeworkAll);
        showContent(getNowAdapterState());
        smartRefreshLayout.finishLoadMore();
    }

    /**
     * 刷新 作业搜索结果 list
     */
    @Override
    public void updateHomeworkSearchRst(LPResHomeworkAllModel searchRst) {
        courseWareAdapter.updateHomeworkSearchRst(searchRst);
        showContent(getNowAdapterState());
        smartRefreshLayout.finishLoadMore();
    }

    /**
     * 刷新 云盘 列表
     */
    @Override
    public void updateAllCloudFile(List<LPCloudFileModel> allCloudFile) {
        courseWareAdapter.updateAllCloudFile(allCloudFile);
        showContent(getNowAdapterState());
        smartRefreshLayout.finishLoadMore();
    }

    /**
     * 刷新路径记录
     *
     * @param dirRecordModels 当前所处目录的所有父级文件夹
     */
    @Override
    public void updateCloudDirRecord(List<LPCloudFileModel> dirRecordModels) {
        this.dirRecordList = dirRecordModels;
        updateFinderRecordView();
        if (dirRecordModels.size() == 0) {
            return;
        }
        List<String> names = new ArrayList<>();
        for (LPCloudFileModel fileModel : dirRecordModels) {
            if (!TextUtils.isEmpty(fileModel.getSearchKey())) {
                names.add(fileModel.getSearchKey());
                break;
            } else {
                names.add(fileModel.getName());
            }
        }
        tvDirRecordMore.updateItems(names);
    }

    /**
     * 教室内存在旧版本不支持作业功能
     */
    public void updateHomeworkSupport(boolean support) {
        this.allIsSupportHomework = support;
        if (homeworkRemindStatus == HomeworkRemindStatus.WaitingForRst && !support) {
            courseWareViewListener.onRemindHomeworkSupport();
            homeworkRemindStatus = HomeworkRemindStatus.HasShowRst;
        }
    }

    /**
     * 文件上传子类回调
     */
    public void onUpload(@NotNull Map<UploadType, String> uploadPath) {
        for (Object key : uploadPath.keySet()) {
            if (!(key instanceof UploadType)) {
                return;
            }
            UploadType uploadType = (UploadType) key;
            String path = uploadPath.get(key);

            // 移动端暂时不支持上传.bds文件，但支持打开，所以不能用 checkAnimFilePathValid 判断，直接在这里过滤掉
            if (path.endsWith(".bds")) {
                showToast(context.getString(R.string.base_tip_file_type_is_not_support));
                return;
            }

            switch (uploadType) {
                case AnimCloudFile:
                    if (checkAnimFilePathValid(path)) {
                        presenter.sendPPTCloudFile(path, true, false);
                    } else {
                        showToast(context.getString(R.string.base_tip_please_upload_ppt_or_pptx));
                    }
                    break;
                case StaticCloudFile:
                    if (checkStaticFilePathValid(path)) {
                        presenter.sendPPTCloudFile(path, false, isImageFile(path));
                    } else {
                        showToast(context.getString(R.string.base_tip_file_type_is_not_support));
                    }
                    break;
                case AnimDoc:
                    // 动态
                    if (checkAnimFilePathValid(path)) {
                        presenter.sendPPTDocument(path, true);
                    } else {
                        showToast(context.getString(R.string.base_tip_please_upload_ppt_or_pptx));
                    }
                    break;
                case StaticDoc:
                    // 静态
                    if (checkStaticFilePathValid(path)) {
                        if (isImageFile(path)) {
                            presenter.sendImageShape(path, false);
                        } else {
                            presenter.sendPPTDocument(path, false);
                        }
                    } else {
                        showToast(context.getString(R.string.base_tip_file_type_is_not_support));
                    }
                    break;
                case HomeWork:
                    if (checkStaticFilePathValid(path)) {
                        presenter.sendHomeWork(path, isImageFile(path));
                    } else {
                        showToast(context.getString(R.string.base_tip_file_type_is_not_support));
                    }
                    break;
                case TransferFromChatImg:
                    if (checkStaticFilePathValid(path)) {
                        presenter.sendChatImageShape(path);
                    } else {
                        showToast(context.getString(R.string.base_tip_file_type_is_not_support));
                    }
                    break;
                default:
                    break;
            }
        }
    }
    // endregion

    // region 工具方法
    private boolean isTeacherOrAssistant() {
        if (getLiveRoom() == null) {
            return false;
        }
        return getLiveRoom().isTeacherOrAssistant();
    }

    private int getDocumentMaxSize() {
        if (getLiveRoom() == null) {
            return 0;
        }
        return getLiveRoom().getPartnerConfig().documentMaxSize;
    }

    private boolean isEnableHomework() {
        if (getLiveRoom() == null) {
            return false;
        }
        return getLiveRoom().getPartnerConfig().enableUseHomeWork == 1;
    }

    private boolean isOrganizationUser() {
        if (getLiveRoom() == null) {
            return false;
        }
        return getLiveRoom().isOrganizationUser();
    }

    private void setVisibility(int id, boolean visible) {
        View view = contentView.findViewById(id);
        if (view != null) {
            view.setVisibility(visible ? View.VISIBLE : View.GONE);
        }
    }

    private void clearEditFocus(View v) {
        v.clearFocus();
        if (v instanceof EditText) {
            InputMethodManager manager = (InputMethodManager) contentView.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void showToast(String message) {
        new ToastUtil(context).setText(message).create().show();
    }

    private boolean checkUploadFileSize(String path) {
        File file = new File(path);
        if (file.exists()) {
            return file.length() / 1024 / 1024 <= getDocumentMaxSize();
        }
        return false;
    }

    /**
     * 变更云盘目录位置
     *
     * @param ind 目录面包屑历史记录的 ind
     */
    private void changeDirPosition(int ind) {
        if (ind < 0 || ind >= dirRecordList.size() - 1) {
            // 合法性检测，注：最后一个为当前所处的目录位置，变更不生效
            return;
        }
        getLiveRoom().getCloudFileVM().requestBackDirRecord(ind);
    }

    private ListState getNowAdapterState() {
        return courseWareAdapter.getItemCount() == 0 ? ListState.Empty : ListState.NotEmpty;
    }
    // endregion

    @Override
    public void onDestroy() {
        super.onDestroy();
        DownLoadManager.getInstance(context).releaseAll();
        presenter.destroy();
        courseWareAdapter.destroy();
        stopLoadingAnim();
    }

    //region 接口实现
    @Override
    public boolean onTouch(View v, @NotNull MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (v.getId() != R.id.window_course_ware_searcher) {
                clearEditFocus(etSearcher);
            }
        }
        return true;
    }

    @Override
    public boolean addUploadModel(LPUploadingDocumentModel model) {
        courseWareAdapter.addUploadModel(model);
        showContent(getNowAdapterState());

        if (!checkUploadFileSize(model.getFilePath())) {
            String errorMsg = String.format(context.getResources().getString(R.string.base_tip_upload_file_over_size), getDocumentMaxSize());
            courseWareAdapter.updateUploadState(model, FileUploadState.UploadFailed,
                    new LPDocTranslateProgressModel(BaseUIConstant.ERROR_CODE_UPLOAD_FAIL_CANT_REUPLOAD_CUSTOM_CODE, errorMsg));
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void removeUploadDocument(String path) {
        contentView.post(() -> courseWareAdapter.removeUpload(path));
    }

    @Override
    public void uploadProgress(String filePath, int progress) {
        // todo lzd 上传进度
    }

    @Override
    public void startTranslate(LPUploadingDocumentModel model) {
        contentView.post(() ->
                courseWareAdapter.updateUploadState(model, FileUploadState.Translating, null));
    }

    @Override
    public void translateProgress(String filePath, int progress) {
        // todo lzd 转码进度
    }

    @Override
    public void uploadFailure(LPUploadingDocumentModel model, String msg) {
        contentView.post(() -> {
            LPDocTranslateProgressModel errorModel =
                    new LPDocTranslateProgressModel(BaseUIConstant.ERROR_CODE_UPLOAD_FAIL_CANT_REUPLOAD_CUSTOM_CODE, msg);
            courseWareAdapter.updateUploadState(model, FileUploadState.UploadFailed, errorModel);
        });
    }

    @Override
    public void translateFailure(LPUploadingDocumentModel model, LPDocTranslateProgressModel progressModel) {
        contentView.post(() ->
                courseWareAdapter.updateUploadState(model, FileUploadState.TranslateFailed, progressModel));
    }

    @Override
    public void onDownloadFailed(String homeworkId, String msg) {
        contentView.post(() -> {
            if (msg != null && msg.toLowerCase().contains("cancel")) {
                showToast(context.getResources().getString(R.string.base_course_manage_cancel_download));
                courseWareAdapter.cancelDownload(homeworkId);
            } else if (msg != null) {
                showToast(msg);
                courseWareAdapter.updateDownloadState(homeworkId, HomeworkDownloadState.DownloadFailed, 0);
            } else {
                showToast(context.getResources().getString(R.string.base_course_manage_download_failed));
            }
        });
    }

    @Override
    public void onDownloadSuccess(String homeworkId) {
        contentView.post(() ->
                courseWareAdapter.updateDownloadState(homeworkId, HomeworkDownloadState.HasDownload, 1));
    }

    @Override
    public void onDownloadProgress(String homeworkId, float progress) {
        contentView.post(() ->
                courseWareAdapter.updateDownloadState(homeworkId, HomeworkDownloadState.Downloading, progress));
    }
    // endregion

    private boolean checkPermission() {
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission((Activity) contentView.getContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            selectImage();
            return true;
        } else {
            this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION_WRITE);
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_WRITE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showToast(getString(R.string.base_request_permission_success));
                    selectImage();
                } else {
                    showToast(getString(R.string.base_request_permission_fail));
                }
                break;
            default:
                break;
        }
    }

    public void selectImage() {
        ThemeConfig.Builder builder = new ThemeConfig.Builder();
        builder.setMainElementsColor(ContextCompat.getColor(context, R.color.base_product_color_50_press));
        BJCommonImageCropHelper.openImageMulti(context, 20, builder.build(), new BJCommonImageCropHelper.OnHandlerResultCallback() {
            @Override
            public void onHandlerSuccess(List<PhotoInfo> list) {
                switch (tabState) {
                    case DocFile:
                        for (PhotoInfo photoInfo : list) {
                            presenter.sendImageShape(photoInfo.getPhotoPath(), false);
                        }
                        break;
                    case CloudFile:
                        for (PhotoInfo photoInfo : list) {
                            presenter.sendPPTCloudFile(photoInfo.getPhotoPath(), false, true);
                        }
                        break;
                    case HomeworkFile:
                        for (PhotoInfo photoInfo : list) {
                            presenter.sendHomeWork(photoInfo.getPhotoPath(), true);
                        }
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onHandlerFailure(String s) {
                showToast(s);
            }
        });
    }
}
